import { http } from '@kit.NetworkKit'
import { Res } from '../entity/Res'

let request = http.createHttp()

export function post<T>(url:string, data:Object):Promise<T> {
  return new Promise<T>((resolve, reject) => {
    request.request(url, {
      method: http.RequestMethod.POST,
      header: {"Content-Type":"application/json"},
      extraData:data
    }).then((response) => {
      if (response.responseCode == 200) {
        let res:Res<T> = JSON.parse(response.result.toString())
        if (res.code == 200) {
          resolve(res.data)
        } else {
          reject(new Error(res.message))
        }
      } else {
        reject(new Error(`网络错误: ${response.responseCode}`))
      }
    })
      .catch((e:Error) => {
        reject(e)
      })
  })
}
export function get<T>(url:string, data?:Object):Promise<T> {
  return new Promise<T>((resolve, reject) => {
    if (data) {
      url += '?' + Object.keys(data).map((k) => `${k}=${data[k]}`).join('&')
    }
    request.request(url)
      .then((response) => {
        if (response.responseCode == 200) {
          let res:Res<T> = JSON.parse(response.result.toString())
          if (res.code == 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.message))
          }
        } else {
          reject(new Error(`网络错误: ${response.responseCode}`))
        }
      })
      .catch((e:Error) => {
        reject(e)
      })
  })
}